package cn.tonyandmoney.warescanapp.rfid

import cn.tonyandmoney.warescanapp.WareApplication
import cn.tonyandmoney.warescanapp.rfid.event.BoundEvent
import cn.tonyandmoney.warescanapp.rfid.event.ConnectEvent
import cn.tonyandmoney.warescanapp.rfid.event.ScanEvent
import cn.tonyandmoney.warescanapp.rfid.event.StateEvent
import cn.tonyandmoney.warescanapp.rfid.listener.RxCommandListener
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
import mpay.sdk.lib.BTLib
import mpay.sdk.lib.interfaces.BluetoothListener
import mpay.sdk.lib.model.DevItem
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info

/**
 * Created by niantuo on 2018/4/1.
 * 扫描工具类
 */
class RFIdUtils : BluetoothListener, AnkoLogger {
    companion object {
        val utils = RFIdUtils()
    }

    var commandLib: BTLib = BTLib(WareApplication.mApp, true)
    val mRxBus = PublishSubject.create<Any>()!!

    init {
        commandLib.btStart()
        commandLib.setBTListener(this)
        commandLib.setCommandListener(RxCommandListener(mRxBus))
    }


    fun scan(): Boolean = commandLib.scanBTDevice()

    public inline fun <reified T : Any> register(): Observable<T> {
        return mRxBus.ofType(T::class.java)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
    }


    private fun onNext(event: Any) {
        info("onNext: $event")
        mRxBus.onNext(event)
    }

    override fun onBluetoothDeviceBoundFailed() {
        onNext(BoundEvent(BoundEvent.CODE_FAILED))
    }

    override fun onBluetoothDeviceBoundSuccess() {
        onNext(BoundEvent(BoundEvent.CODE_SUCCESS))
    }

    override fun onBluetoothDeviceBounding() {
        onNext(BoundEvent(BoundEvent.CODE_BOUNDING))
    }

    override fun onBluetoothDeviceConnectFailed() {
        onNext(ConnectEvent(ConnectEvent.CODE_FAILED))
    }

    override fun onBluetoothDeviceConnected() {
        onNext(ConnectEvent(ConnectEvent.CODE_SUCCESS))
    }

    override fun onBluetoothDeviceConnecting() {
        onNext(ConnectEvent(ConnectEvent.CODE_CONNECTING))
    }

    override fun onBluetoothDeviceDisconnected() {
        onNext(ConnectEvent(ConnectEvent.CODE_DISCONNECTED))
    }

    override fun onBluetoothDeviceFound(devItem: DevItem) {
        onNext(ScanEvent(ScanEvent.DEVICE_FOUND, devItem))
    }

    override fun onBluetoothDeviceScanOver() {
        onNext(ScanEvent(ScanEvent.OVER))
    }

    override fun onBluetoothDeviceScaning() {
        onNext(ScanEvent(ScanEvent.SCANNING))
    }

    override fun onBluetoothState(state: Boolean) {
        onNext(StateEvent(state))
    }
}